import React, { useEffect, useState } from "react";
import {
  Button,
  Flex,
  AutoComplete,
  Table,
  Divider,
  Modal,
  message,
  Input,
  Form,
  Upload,
} from "antd";
import {
  DeleteOutlined,
  SearchOutlined,
  LoadingOutlined,
  PlusOutlined,
} from "@ant-design/icons";
import styles from "../../assets/css/MedicalFrontline/PrescriptionReceipts.module.css";
import type { TableColumnsType, TableProps } from "antd";
import {
  delPreReceiptsMore,
  delPreReceiptsRow,
  getPreReceiptsList,
  AddPrescription,
  AddMedicines,
  AddImg,
} from "../../api/MedicalFrontline/PrescriptionReceipts";
import { useSelector } from "react-redux";

// 定义接口数据类型
interface DataType {
  id: number;
  drugsname: string;
  img: string;
  type: string;
  price: string;
  count: string;
  endtime: string;
  other: string;
  selected: boolean;
}
// 上传图片
// type FileType = Parameters<GetProp<UploadProps, "beforeUpload">>[0];
// const getBase64 = (img: FileType, callback: (url: string) => void) => {
//   const reader = new FileReader();
//   reader.addEventListener("load", () => callback(reader.result as string));
//   reader.readAsDataURL(img);
// };
// const beforeUpload = (file: FileType) => {
//   const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
//   if (!isJpgOrPng) {
//     message.error("You can only upload JPG/PNG file!");
//   }
//   const isLt2M = file.size / 1024 / 1024 < 2;
//   if (!isLt2M) {
//     message.error("Image must smaller than 2MB!");
//   }
//   return isJpgOrPng && isLt2M;
// };

export default function PrescriptionReceipts() {
  const [list, setList] = useState<DataType[]>([]);
  const [other, setOther] = useState<{ [key: string]: string }>({});
  const [counts, setCounts] = useState<{ [key: string]: string }>({});
  const [filteredData, setFilteredData] = useState<DataType[]>([]);
  const [searchText, setSearchText] = useState<string>("");
  const [options, setOptions] = useState<{ label: string; value: string }[]>(
    []
  );
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
  const user = useSelector((state) => state.userSlice.user);
  const [totalPrice, setTotalPrice] = useState<number>(0); // 存储总价
  const [isModalVisible, setIsModalVisible] = useState(false); // 控制模态框显示
  const [medicineData, setMedicineData] = useState({
    name: "",
    sort: "",
    type: "",
    starttime: "",
    endtime: "",
    count: "",
    price: "",
    img: "",
  });
  const initialization = async () => {
    try {
      const res = await getPreReceiptsList();
      console.log(res);

      setList(
        res.data.map((item) => ({ ...item, selected: false })) as DataType[]
      );
      setFilteredData(
        res.data.map((item) => ({ ...item, selected: false })) as DataType[]
      );
      setOptions(
        res.data.map((item) => ({
          label: item.drugsname,
          value: item.drugsname,
        }))
      );
      // 初始化counts状态
      const initialCounts = res.data.reduce((acc, item) => {
        acc[item.id.toString()] = item.count;
        return acc;
      }, {});
      setCounts(initialCounts);
    } catch (err) {
      console.log("获取数据失败：", err);
    }
  };
  useEffect(() => {
    initialization();
  }, []);
  const columns: TableColumnsType<DataType> = [
    // 药品名称
    {
      title: "药品名称",
      dataIndex: "drugsname",
    },
    // 药品图片
    {
      title: "药品图片",
      dataIndex: "img",
      render: (imgUrl: string) => (
        <img
          src={imgUrl}
          alt="药品图片"
          style={{ width: "50px", height: "50px" }} // 可以根据需要调整样式
          onError={(e) => {
            // 当图片加载失败时，设置默认图片
            e.target.src =
              "https://tse4-mm.cn.bing.net/th/id/OIP-C.N_jgczL0F1LnUWytCsrQ7QHaHa?rs=1&pid=ImgDetMain"; // 请替换为实际的默认图片URL
          }}
        />
      ),
    },
    // 药品规格
    {
      title: "药品规格",
      dataIndex: "type",
    },
    // 药品单价
    {
      title: "药品单价",
      dataIndex: "price",
    },
    // 药品数量
    {
      title: "药品数量",
      dataIndex: "count",
      render: (text: string, row: DataType) => {
        return (
          <div style={{ display: "flex", alignItems: "center" }}>
            <Button
              color="default"
              variant="filled"
              onClick={() => countMinus(row.id)}
            >
              -
            </Button>
            <Input
              type="text"
              value={counts[row.id.toString()] || text}
              onChange={handleCountNum(row.id)}
              style={{ width: "50px" }}
            />
            <Button
              color="default"
              variant="filled"
              onClick={() => countAdd(row.id)}
            >
              +
            </Button>
          </div>
        );
      },
    },
    // 药品有效期
    {
      title: "药品有效期",
      dataIndex: "endtime",
      render: (text: string) => {
        const date = new Date(text);
        const year = date.getFullYear();
        // 月份从0开始，所以需要加1
        const month = date.getMonth() + 1;
        const day = date.getDate();
        const timeDate = `${year}-${month.toString().padStart(2, "0")}-${day
          .toString()
          .padStart(2, "0")}`;
        return <>{timeDate}</>;
      },
    },
    // 药品备注
    {
      title: "用量备注",
      dataIndex: "other",
      render: (text: string, row: DataType) => {
        return (
          <div>
            <Input
              type="text"
              value={other[row.id.toString()] || ""}
              onChange={handleOther(row.id)}
              style={{ width: "100px" }}
            ></Input>
          </div>
        );
      },
    },
    // 药品操作
    {
      title: "操作",
      render: (row: DataType) => {
        return (
          <>
            <DeleteOutlined
              style={{ color: "#adefef", cursor: "pointer" }}
              onClick={() => DeleteRow(row.id)}
            />
          </>
        );
      },
    },
  ];
  // 计算总价的函数
  const calculateTotalPrice = () => {
    let total = 0;
    // 遍历列表中的所有项目
    list.forEach((item) => {
      if (item.selected) {
        // 获取当前项目的数量，如果counts中有则使用counts中的，否则使用项目本身的数量
        const count = parseInt(counts[item.id.toString()] || item.count, 10);
        // 获取项目的价格并转换为浮点数
        const price = parseFloat(item.price);
        // 计算当前项目的总价并累加到total中
        total += price * count;
      }
    });
    // 设置总价状态
    setTotalPrice(total);
  };
  // 备注输入框
  // 备注输入框
  const handleOther =
    (rowId: number) => (e: React.ChangeEvent<HTMLInputElement>) => {
      const newValue = e.target.value;
      setOther((other) => ({
        ...other,
        [rowId]: newValue,
      }));
    };
  // 删除
  const DeleteRow = (rowId: number) => {
    Modal.confirm({
      title: "提示",
      content: "确定要删除吗？删除后数据不可恢复！！",
      okText: "确定",
      cancelText: "取消",
      onOk: async () => {
        delPreReceiptsRow(rowId)
          .then((res) => {
            if (res.code === 1) {
              message.success(res.msg);
              initialization();
            }
            message.info(res.msg);
          })
          .catch((err) => {
            console.log(err);
          });
      },
      onCancel() {
        console.log("取消删除");
        message.info("取消删除");
      },
    });
    console.log(rowId);
  };
  // 批量删除
  const DeleteMore = () => {
    if (selectedRowKeys.length === 0) {
      message.warning("请选择要删除的项");
      return;
    }
    Modal.confirm({
      title: "提示",
      content: "确定要删除选中项吗？删除后数据不可恢复！！",
      okText: "确定",
      cancelText: "取消",
      onOk: async () => {
        const idsToDelete = selectedRowKeys.join(",");
        delPreReceiptsMore(`[${idsToDelete}]`)
          .then((res) => {
            if (res.code === 1) {
              message.success(res.msg);
              initialization();
            } else {
              message.error("删除失败");
            }
          })
          .catch((err) => {
            console.log(err);
            message.error("删除失败");
          });
      },
      onCancel() {
        console.log("取消删除");
        message.info("取消删除");
      },
    });
  };
  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      setSelectedRowKeys(selectedRowKeys);
      console.log(selectedRowKeys);
      console.log(selectedRows);

      const newList = list.map((item) => {
        if (selectedRowKeys.includes(item.id)) {
          return { ...item, selected: true };
        } else {
          return { ...item, selected: false };
        }
      });
      setList(newList);
      calculateTotalPrice(); // 更新总价
    },
    getCheckboxProps: (record) => ({
      checked: record.selected,
    }),
  };
  // 添加药品数量和减去药品数量
  const handleCountNum =
    (rowId: number) => (e: React.ChangeEvent<HTMLInputElement>) => {
      const newValue = e.target.value;
      setCounts((counts) => ({
        ...counts,
        [rowId]: newValue,
      }));
      calculateTotalPrice(); // 更新总价
    };

  // 添加药品数量
  const countAdd = (id: number) => {
    setCounts((counts) => {
      const newList = { ...counts };
      const currentCount = parseInt(newList[id.toString()], 10) || 0;
      newList[id.toString()] = String(currentCount + 1);
      calculateTotalPrice(); // 更新总价
      return newList;
    });
  };

  // 减去药品数量
  const countMinus = (id: number) => {
    setCounts((counts) => {
      const newList = { ...counts };
      const currentCount = parseInt(newList[id.toString()], 10) || 0;
      if (currentCount > 0) {
        newList[id.toString()] = String(currentCount - 1);
        calculateTotalPrice(); // 更新总价
      }
      return newList;
    });
  };
  // 查询
  const handleSearchInputChange = (value: string) => {
    setSearchText(value);
    if (value.trim()) {
      filterData(value);
    } else {
      setFilteredData(list); // 输入框为空时显示所有数据
    }
  };

  const filterData = (searchText: string) => {
    const filtered = list.filter((item) =>
      item.drugsname.toLowerCase().includes(searchText.toLowerCase())
    );
    setFilteredData(filtered);
  };

  const handleSearch = () => {
    filterData(searchText);
  };
  useEffect(() => {
    filterData(searchText);
  }, [searchText, list]);
  // 开具处方
  // 开具处方
  const handleAddPrescription = () => {
    const selectedRecipes = list.filter((item) => item.selected);

    // 获取最新的用量备注数据
    const updatedOtherData = Object.keys(other).reduce((acc, key) => {
      const id = parseInt(key);
      const item = selectedRecipes.find((item) => item.id.toString() === key);
      if (item) {
        acc[id] = other[key];
      }
      return acc;
    }, {});

    // 将用量备注数据映射到selectedRecipes中
    const recipel = selectedRecipes.map((item) => ({
      drugsname: item.drugsname,
      img: item.img,
      type: item.type,
      price: item.price,
      count: item.count,
      endtime: item.endtime,
      other: updatedOtherData[item.id] || item.other, // 使用最新的用量备注数据
    }));

    // 调用添加处方的API
    const prescriptionData = {
      doctorid: user.id, // 假设医生id为1
      recipel: JSON.stringify(recipel),
      price: totalPrice,
    };

    AddPrescription(prescriptionData)
      .then((res) => {
        if (res.code === 1) {
          message.success("处方开具成功");
          initialization(); // 重置数据
        } else {
          message.error("处方开具失败");
        }
      })
      .catch((err) => {
        console.log(err);
        // message.error("处方开具失败");
      });
  };
  // 添加药品
  // 表单数据
  // const [loading, setLoading] = useState(false);
  // const [imageUrl, setImageUrl] = useState<string>();
  // const showModal = () => {
  //   setIsModalVisible(true);
  // };

  // const handleOk = () => {
  //   // 提交表单数据
  //   AddMedicines(medicineData)
  //     .then((res) => {
  //       if (res.code === 1) {
  //         message.success("药品添加成功");
  //         setIsModalVisible(false); // 关闭模态框
  //         initialization(); // 重新加载数据
  //       } else {
  //         message.error("药品添加失败");
  //       }
  //     })
  //     .catch((err) => {
  //       console.log(err);
  //       message.error("药品添加失败");
  //     });
  // };

  // const handleCancel = () => {
  //   setIsModalVisible(false); // 关闭模态框
  // };
  // const handleInputChange = (e) => {
  //   const { name, value } = e.target;
  //   setMedicineData((prev) => ({ ...prev, [name]: value }));
  // };

  // // 上传图片
  // const handleImageUpload = async (info) => {
  //   if (info.file.status === "uploading") {
  //     setLoading(true);
  //     return;
  //   }
  //   if (info.file.status === "done") {
  //     try {
  //       // 使用AddImg接口上传图片
  //       const response = await AddImg(info.file.originFileObj);
  //       if (response.code === 1) {
  //         // 假设服务器返回的文件名在response.fileName中
  //         setMedicineData((prev) => ({ ...prev, img: response.fileName }));
  //         message.success("图片上传成功");
  //       } else {
  //         message.error("图片上传失败");
  //       }
  //     } catch (error) {
  //       console.error("Error uploading image:", error);
  //       message.error("图片上传失败");
  //     } finally {
  //       setLoading(false);
  //     }
  //   }
  // };
  return (
    <div className={styles.bigBox}>
      <div className={styles.head}>
        <div className={styles.left}>
          <AutoComplete
            options={options}
            style={{ width: 200 }}
            defaultValue={searchText}
            placeholder="请输入药品/器材/疫苗名称"
            onChange={(value) => handleSearchInputChange(value)}
            onPress={(event) => {
              if (event.key === "Enter") {
                handleSearch();
              }
            }}
          />
          <Flex gap="small" wrap>
            <Button type="primary" onClick={handleSearch}>
              <SearchOutlined />
              查询
            </Button>
          </Flex>
        </div>
        <div className={styles.right}>
          {/* <Flex gap="small" wrap> */}
          {/* <Button type="primary" onClick={showModal}>
              添加药品
            </Button>
            <Modal
              title="添加药品"
              open={isModalVisible}
              onOk={handleOk}
              onCancel={handleCancel}
            >
              <Form
                layout="vertical"
                name="add_medicine"
                initialValues={medicineData}
                onFinish={handleOk}
              >
                <Form.Item
                  name="name"
                  label="药品/耗材名称"
                  rules={[{ required: true, message: "请输入药品/耗材名称!" }]}
                >
                  <Input onChange={handleInputChange} />
                </Form.Item>
                <Form.Item
                  name="sort"
                  label="药品分类"
                  rules={[{ required: true, message: "请输入药品分类!" }]}
                >
                  <Input onChange={handleInputChange} />
                </Form.Item>
                <Form.Item
                  name="type"
                  label="药品规格"
                  rules={[{ required: true, message: "请输入药品规格!" }]}
                >
                  <Input onChange={handleInputChange} />
                </Form.Item>
                <Form.Item
                  name="starttime"
                  label="生产日期"
                  rules={[{ required: true, message: "请输入生产日期!" }]}
                >
                  <Input onChange={handleInputChange} />
                </Form.Item>
                <Form.Item
                  name="endtime"
                  label="有效日期"
                  rules={[{ required: true, message: "请输入有效日期!" }]}
                >
                  <Input onChange={handleInputChange} />
                </Form.Item>
                <Form.Item
                  name="count"
                  label="药品数量"
                  rules={[{ required: true, message: "请输入药品数量!" }]}
                >
                  <Input onChange={handleInputChange} />
                </Form.Item>
                <Form.Item
                  name="price"
                  label="药品价格"
                  rules={[{ required: true, message: "请输入药品价格!" }]}
                >
                  <Input onChange={handleInputChange} />
                </Form.Item>
                <Form.Item name="img" label="上传药品/耗材图片">
                  <Upload
                    name="avatar"
                    listType="picture-card"
                    className="avatar-uploader"
                    showUploadList={false}
                    beforeUpload={beforeUpload}
                    onChange={handleImageUpload} // 使用handleImageUpload处理上传
                  >
                    {imageUrl ? (
                      <img
                        src={imageUrl}
                        alt="avatar"
                        style={{ width: "100%" }}
                      />
                    ) : (
                      <button
                        style={{ border: 0, background: "none" }}
                        type="button"
                      >
                        {loading ? <LoadingOutlined /> : <PlusOutlined />}
                        <div style={{ marginTop: 8 }}>上传图片</div>
                      </button>
                    )}
                  </Upload>
                </Form.Item>
                <Form.Item>
                  <Button type="primary" htmlType="submit">
                    提交
                  </Button>
                  <Button htmlType="button" onClick={handleCancel}>
                    取消
                  </Button>
                </Form.Item>
              </Form>
            </Modal> */}
          <Button onClick={DeleteMore}>删除选中</Button>
          {/* </Flex> */}
        </div>
      </div>
      <div className={styles.table}>
        <Divider />
        <Table<DataType>
          rowSelection={rowSelection}
          columns={columns}
          dataSource={filteredData}
          rowKey={(row) => row.id}
          pagination={{ pageSize: 5 }}
        />
      </div>
      <div className={styles.bottom}>
        总价:{totalPrice}元 医生签名:{" "}
        <Input type="text" style={{ width: "100px" }}></Input>
        <Flex gap="small" wrap>
          <Button type="primary" onClick={handleAddPrescription}>
            开具处方
          </Button>
        </Flex>
      </div>
    </div>
  );
}
